package com.sscw.tcp.mqtt;

import com.alibaba.mqtt.server.ServerProducer;
import com.alibaba.mqtt.server.common.SendResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@AllArgsConstructor
public class MQTTProducer {

    private final ServerProducer serverProducer;
    private final MqttClient mqttClient;

    public SendResult sendMessage(String topic, String message) throws IOException {
        log.info("发送mqtt消息，topic：{}，message：{}", topic, message);
        return serverProducer.sendMessage(topic, message.getBytes(StandardCharsets.UTF_8));
    }

    public void sendIoMessage(String topic, String message, Integer qosLevel) throws MqttException {
        log.info("终端发送mqtt消息，topic：{}，message：{}", topic, message);
        MqttMessage sendMessage = new MqttMessage(message.getBytes());
        sendMessage.setQos(qosLevel);
        mqttClient.publish(topic, sendMessage);
    }

}
